#include <stdio.h>   // sscanf()
#include <math.h>    // fabs()
#include <stdlib.h>  // exit()
#include <string.h>  // strncpy()
#include <unistd.h>  // _exit()
#include <signal.h>

#include "rcs.hh"               // ZUC NML
#include "nml_intf/zuc.hh"      // ZUC NML
#include "nml_intf/zuc_nml.hh"  // ZUC NML
#include "nml_intf/zucglb.h"    // zucGetArgs(), ZUC_NMLFILE
#include "rcs_print.hh"
#include "nml_oi.hh"
#include "timer.hh"
#include "nml_srv.hh"  // run_nml_servers()

static RCS_CMD_CHANNEL* zucCommandChannel = NULL;
static RCS_STAT_CHANNEL* zucStatusChannel = NULL;
static NML* zucErrorChannel = NULL;

void runZucSvr() { run_nml_servers(); }
int initZucSvr(int argc, char* argv[])
{
    if (0 != zucGetArgs(argc, argv))
    {
        rcs_print_error("Error in argument list\n");
        exit(1);
    }
    // get configuration information
    double start_time = etime();

    while (fabs(etime() - start_time) < 10.0 && (zucCommandChannel == NULL || zucStatusChannel == NULL || zucErrorChannel == NULL))
    {
        if (NULL == zucCommandChannel)
        {
            zucCommandChannel = new RCS_CMD_CHANNEL(zucFormat, "zucCommand", "zucsvr", zuc_nmlfile);
        }
        if (NULL == zucStatusChannel)
        {
            zucStatusChannel = new RCS_STAT_CHANNEL(zucFormat, "zucStatus", "zucsvr", zuc_nmlfile);
        }
        if (NULL == zucErrorChannel)
        {
            zucErrorChannel = new NML(nmlErrorFormat, "zucError", "zucsvr", zuc_nmlfile);
        }

        if (!zucCommandChannel->valid())
        {
            delete zucCommandChannel;
            zucCommandChannel = NULL;
        }
        if (!zucStatusChannel->valid())
        {
            delete zucStatusChannel;
            zucStatusChannel = NULL;
        }
        if (!zucErrorChannel->valid())
        {
            delete zucErrorChannel;
            zucErrorChannel = NULL;
        }
        esleep(0.200);
    }

    if (NULL == zucCommandChannel)
    {
        zucCommandChannel = new RCS_CMD_CHANNEL(zucFormat, "zucCommand", "zucsvr", zuc_nmlfile);
    }
    if (NULL == zucStatusChannel)
    {
        zucStatusChannel = new RCS_STAT_CHANNEL(zucFormat, "zucStatus", "zucsvr", zuc_nmlfile);
    }
    if (NULL == zucErrorChannel)
    {
        zucErrorChannel = new NML(nmlErrorFormat, "zucError", "zucsvr", zuc_nmlfile);
    }
    return 0;
}
